package me.jzn.alib.drawable;

import android.content.pm.ApplicationInfo;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.widget.ImageView;
import android.widget.RemoteViews;

import androidx.annotation.IdRes;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;

import me.jzn.alib.ALib;

public interface DrawableType {
    public static DrawableType fromFile(File file) {
        return new FileDrawableType(file);
    }

    public static DrawableType fromUri(Uri uri) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return new IconDrawableType(Icon.createWithContentUri(uri));
        } else {
            try {
                InputStream is = ALib.app().getContentResolver().openInputStream(uri);
                return new DefaultDrawableType(Drawable.createFromResourceStream(ALib.app().getResources(), null, is, null));
            } catch (FileNotFoundException e) {
                //Caused by: java.io.FileNotFoundException: open failed: EACCES (Permission denied)
                throw new IllegalArgumentException("无法找到uri:" + uri);
            }
        }
    }

    public static DrawableType fromLogo(ApplicationInfo appInfo) {
        if (appInfo.icon != 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //当getDrawable的时候，会抛出Resources$NotFoundException
            return new IconDrawableType(Icon.createWithResource(appInfo.packageName, appInfo.icon));
        }
        return new DefaultDrawableType(appInfo.loadIcon(ALib.app().getPackageManager()));
    }

    public Drawable getDrawable();

    public void setImageView(ImageView iv);

    public void setBackground(View view);

    public void setRemoteViews(RemoteViews rv, @IdRes int imageViewId);
}
